/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package persistence;

import java.io.File;

import lombok.AccessLevel;
import lombok.Getter;

import org.openrdf.model.Statement;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.config.RepositoryConfigException;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.object.ObjectRepository;
import org.openrdf.repository.object.config.ObjectRepositoryFactory;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.nativerdf.NativeStore;

public class AlibabaObjectRepository {
	public static final String REPOSITORY_PATH="/tmp/ActivityServerRepository";

	@Getter(AccessLevel.PRIVATE)
	private static ObjectRepositoryFactory objectRepositoryFactory = new ObjectRepositoryFactory();

	@Getter(AccessLevel.PUBLIC)
	private static ObjectRepository instance;

	private static ObjectConnection connection;

	static {
		Repository rdfRepository = new SailRepository(new NativeStore(new File(REPOSITORY_PATH)));
		try {
			rdfRepository.initialize();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}

		try {
			instance = getObjectRepositoryFactory().createRepository(
					rdfRepository);
		} catch (RepositoryConfigException e) {
			e.printStackTrace();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}

	}

	/**
	 * get a connection to the ObjectRepository to perform operations on it.
	 * 
	 * @return
	 */
	public static ObjectConnection getConnection() {
		if (null == connection) {
			try {
				connection = getInstance().getConnection();
			} catch (RepositoryException e) {

			}
		}
		return connection;
	}

	public static void dumpRepository()
			throws RepositoryException {
		RepositoryResult<Statement> statements = getConnection().getStatements(
				null, null, null, null);
		for (final Statement s: statements.asList()) 
		{
			System.out.println(s.getSubject().stringValue()+" "+s.getPredicate().stringValue()+" " +s.getObject().stringValue() );
		}
	}
	
	public static void clearRepository() throws RepositoryException {
		getConnection().clear( null);
	}

}
